const Koa = require('koa')
const router = require('koa-router')()
const bodyparer = require('koa-bodyparser')
const cors = require('koa-cors')

let app = new Koa()

const { Sequelize, Op, DataTypes } = require('sequelize')

const sequelize = new Sequelize('exam', 'postgres', 'i02BIth18tH@lhT_ao', {
    host: 'godme.top',
    dialect: 'postgres'
})

let Blog = sequelize.define('blog', {
    tite:{
        type:DataTypes.STRING,
        allowNull:false
    },
    imports:{
        type:DataTypes.STRING,
        allowNull:false
    },
    text:{
        type:DataTypes.STRING,
        allowNull:false
    },
    cat:{
        type:DataTypes.STRING,
        allowNull:false
    },
    atou:{
        type:DataTypes.STRING,
        allowNull:false
    },
    time:{
        type:DataTypes.STRING,
        allowNull:false
    },
})

// sequelize.sync({ force: true }).then(() => {
//     Blog.bulkCreate([
//         {
//             tite: '论ef core',
//             imports: '摘要1',
//             text: '我是内容',
//             cat: '分类1',
//             atou: '作者1',
//             time: '2022-04-07',
//         }
//     ])
// })

router.get('/blog', async (ctx, next) => {
    let keyword = ctx.query.keyword || ''
    console.log(keyword);
    if (keyword) {
        let list = await Blog.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN ? parseInt(keyword) : 0 },
                    { tite: keyword },
                    { imports: keyword },
                    { text: keyword },
                    { cat: keyword },
                    { atou: keyword },
                    { time: keyword },
                ]
            },
            order: ['id']
        })
        ctx.body = list
    }else{
        let list = await Blog.findAll({
            order:['id']
        })
        ctx.body = list
    }
})

router.delete('/blog/:id', async (ctx, next) => {
    let id = ctx.request.params.id
    console.log(id);
    await Blog.destroy({where:{id:id}})
    ctx.body = await Blog.findAll({order:['id']})
})

router.put('/blog/:id', async (ctx, next) => {
    let id = ctx.request.params.id
    let obj = ctx.request.body
    console.log(obj);
    await Blog.update(obj,{
        where:{id:id}
    })
    ctx.body = {
        code:1000,
        data:obj,
    }
})

router.post('/blog', async (ctx, next) => {
    let obj = ctx.request.body
    await Blog.create(
        {
            tite:obj.tite,
            imports:obj.imports,
            text:obj.text,
            cat:obj.cat,
            atou:obj.atou,
            time:obj.time,
        }
    )
    ctx.body={
        code:1000,
        msg:'添加成功'
    }
})

router.get('/blog/:id', async (ctx, next) => {
    console.log(1111);
    let id = ctx.request.params.id
    console.log(id);
    ctx.body = await Blog.findByPk(id)
})


app.use(cors())
app.use(bodyparer())
app.use(router.routes())

app.listen(8000, () => {
    console.log('http://localhost:8000');
})